import React, { useRef, useEffect } from "react";
import {
    MeshNormalMaterial, Mesh, DoubleSide, Object3D,
    Matrix4, Vector3, MeshBasicMaterial, SphereGeometry, MeshPhongMaterial, Color, PointLight, Group, Object3DEventMap,
} from 'three';
import Stage from '../component/Stage';
import Axis from '../component/Axis';
import { GUI } from 'dat.gui'

const stage = new Stage(window.innerWidth, window.innerHeight, new Vector3(0, 20, 0), new Vector3());
const { scene, renderer } = stage;

const meshArr: Object3D[] = [];

const light = new PointLight(new Color(1, 1, 1), 10);
scene.add(light);



//太阳系
const solarSystem = new Group();
scene.add(solarSystem);
meshArr.push(solarSystem);

//地球系
const earthSystem = new Group();
earthSystem.position.x = 5;
scene.add(earthSystem);
meshArr.push(earthSystem);
solarSystem.add(earthSystem);

//月亮系
const moonSystem = new Group();
moonSystem.position.x = 2;
scene.add(moonSystem);
meshArr.push(moonSystem);
earthSystem.add(moonSystem);

const geo = new SphereGeometry(1, 6, 6);

//太阳
const sunMush = new Mesh(geo, new MeshPhongMaterial({ emissive: new Color(1, 0, 0) }));
meshArr.push(sunMush);
solarSystem.add(sunMush);
//地球
const earthMush = new Mesh(geo, new MeshPhongMaterial({ emissive: new Color(0, 0, 1) }));
earthMush.scale.set(0.5, 0.5, 0.5);
meshArr.push(earthMush);
earthSystem.add(earthMush);
//月亮
const moonMush = new Mesh(geo, new MeshPhongMaterial({ emissive: new Color(0.6, 0.6, 0.6) }));
moonMush.scale.set(0.3, 0.3, 0.3);
meshArr.push(moonMush);
moonSystem.add(moonMush);


stage.beforeRender = (time) => {
    meshArr.forEach(obj => {
        obj.rotation.y = time * 0.001;
    })
}

const gui = new GUI({ autoPlace: false });
const axisGUI = function (obj: Object3D, label: string) {
    const helper = new Axis(obj, 2);
    gui.add(helper, 'visible').name(label);
}

axisGUI(solarSystem, '太阳系');
axisGUI(earthSystem, '地球系');
axisGUI(moonSystem, '月亮系');


let isRender: number = 0;
const CustomGeo = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(gui.domElement);
            current.append(renderer.domElement);
        }
        if (isRender == 0)
            stage.animate();
        isRender++;
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default CustomGeo;